package com.htj.powerbank.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.htj.powerbank.entity.Shop;
import com.htj.powerbank.service.QrCodeService;
import com.htj.powerbank.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

@RestController
public class QrCodeController {

    @Autowired
    private QrCodeService codeService;

    @Autowired
    private ShopService shopService;

    //生成二维码并将其返回给前端调用者_hutool
    @PostMapping("generate/v3")
    public R generateV3(@RequestParam("id") int id, HttpServletResponse servletResponse){
        JSONObject jsonObject = new JSONObject();
        List<Shop> content = shopService.getShopListbyid(id);
        try {
            //将生成的二维码文件存放于文件目录中
            String type = "images\\qrcode\\";
            String  realPath = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\" + type;
            File dir = new File(realPath);
            if (!dir.isDirectory()){
                dir.mkdirs();
            }
            codeService.createCodeToFile(JSONObject.parseObject(content.toString()),realPath+id+".png");

            //将生成的二维码文件直接返回给前端响应流
            codeService.createCodeToStream(JSONObject.parseObject(content.toString()),servletResponse);
            jsonObject.put("code", 200);
        }catch (Exception e){
            jsonObject.put("code", 201);
        }
        return R.ok(jsonObject);
    }
}
